package cn.tedu.boot15.controller;

import cn.tedu.boot15.entity.User;
import cn.tedu.boot15.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.security.util.Password;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class UserController {
    @RequestMapping("/reg")
    @ResponseBody
    public String reg(User user){
        //soutp
        System.out.println("user = " + user);
        //获取数据库连接
        /**
         * use empdb
         * drop table user;
         * create table user(id int primary key auto_increment,
         *   username varchar(50), password varchar(50),age int);
         */
        try (Connection conn= DBUtils.getConn()){
            String sql="insert into user values(null,?,?,?,?)";
            //因为有变量所以使用预编译的对象
            PreparedStatement ps=conn.prepareStatement(sql);
            //替换 ?号的内容
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getNick());
            ps.setInt(4,user.getAge());
            //执行
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "注册成功!";
    }
    @RequestMapping("/login")
    @ResponseBody
    public String login(User user){
        System.out.println("user = " + user);
        //获取连接
        try (Connection conn=DBUtils.getConn()){
            String sql="select password from user where username=?";
            PreparedStatement ps=conn.prepareStatement(sql);
            //替换 ?
            ps.setString(1,user.getUsername());
            //执行查询
            ResultSet rs=ps.executeQuery();
            if (rs.next()){//查到了 代表用户存在
                //得到查询到的密码
                String password=rs.getString(1);
                //判断用户输入和查询到的密码是否一致
                if (password.equals(user.getPassword())){
                    return "登录成功!";
                }else {
                    return "密码错误!";
                }
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "用户不存在!";
    }
}

